package com.example.nettypractice.client;

import com.example.nettypractice.info.TransportData;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.Date;

/**
 * 客户端的handler，负责对数据以及连接进行操作
 */
@ChannelHandler.Sharable
public class FirstNettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private TransportData getTransportData(){
        TransportData data = new TransportData("NettyTest", new Date(System.currentTimeMillis()), "nettt对象序列化传输测试");
        return data;
    }
    //每当接收数据时，都会调用。但需要注意的是服务器发送的消息可能会被分块接受
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("client received "  + byteBuf.toString(CharsetUtil.UTF_8));
    }

    //将在连接建立时被调用，确保了数据将会被尽可能快速地写入服务器。
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端启动");
        super.channelActive(ctx);
        ctx.writeAndFlush(getTransportData());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }
    //当连接不上服务器时，会被调用，进行异常处理。
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        System.out.println("can't connect server");
        cause.printStackTrace();
        ctx.close();
    }
}
